package com.dituhui.gps.service;

import java.io.IOException;

import org.apache.log4j.Logger;

import net.sf.json.JSONObject;

import com.dituhui.tool.gis.CoordConverter;
import com.dituhui.tool.gis.Point;
import com.dituhui.tool.io.Constants;
import com.dituhui.tool.io.HttpTool;
import com.dituhui.tool.util.StringUtil;

/**
 * 逆地址解析
 * 
 * @author liweigu
 * 
 */
public class DeAddressMatch {
	private static Logger LOGGER = Logger.getLogger(DeAddressMatch.class);
	// 从配置文件读取URL模板
	private static String URL = Constants.getValue("DeAddressMatchURL", "gps_config.properties");

	/**
	 * 根据坐标获取地址
	 * 
	 * @param x 经纬度X
	 * @param y 经纬度Y
	 * @return 地址（省市区）
	 */
	public String getAddress(double x, double y) {
		String address = null;

		Point point = new Point(x, y);
		Point mercatorPoint;
		if (x > 360) {
			// 传入的是摩卡托坐标
			mercatorPoint = point;
		} else {
			// 传入的是经纬度坐标
			mercatorPoint = CoordConverter.lngLatToMercator(point);
		}

		// TODO: http调用方式要改成dubbo调用
		// 复制url，避免多线程里同时修改url
		String copyUrl = new String(URL);
		// 以配置文件里的url为模板，替换x/y参数
		String actionUrl = copyUrl.replace("#x#", "" + mercatorPoint.x).replace("#y#", "" + mercatorPoint.y);
		// String actionUrl = copyUrl.replace("#x#", "" + x).replace("#y#", "" + y);
		// System.out.println(actionUrl);
		// 调用http服务获取结果
		String queryResult = null;
		try {
			queryResult = HttpTool.getContentByGET(actionUrl, null);
		} catch (IOException e) {
			LOGGER.info("getAddress发生异常。url=" + actionUrl);
		}
		// System.out.println("result=" + result);
		if (queryResult != null) {
			// [{"code":"1","country":"中国","province":"上海市","city":" ","district":"闵行区","street":"万源路３７９号复旦大学附属儿科医院","address":"复旦大学附属儿科医院－门诊","point":{"x":121.3953423500061,"y":31.139352321624756,"id":0}}]
			// 去掉result前后的大括号，得到json内容。
			queryResult = queryResult.substring(1, queryResult.length() - 1);
			JSONObject jsonObject = JSONObject.fromObject(queryResult);
			String province = jsonObject.getString("province");
			// 服务返回null字符串的，设置为空。
			if (province == null || StringUtil.NULL.equalsIgnoreCase(province)) {
				province = "";
			}
			String city = jsonObject.getString("city");
			if (city == null || StringUtil.NULL.equalsIgnoreCase(city.trim())) {
				city = "";
			} else {
				city = city.trim();
			}
			String district = jsonObject.getString("district");
			if (district == null || StringUtil.NULL.equalsIgnoreCase(district)) {
				district = "";
			}
			String addressInJson = jsonObject.getString("address");
			if (addressInJson == null || StringUtil.NULL.equalsIgnoreCase(addressInJson)) {
				addressInJson = "";
			}
			// 对于直辖市，省名和市名相同，将省名置空避免重复
			if (province != null && province.equals(city)) {
				province = "";
			}
			if (city != null && city.equals(district)) {
				district = "";
			}
			address = province + city + district + addressInJson;
		}

		return address;
	}
}
